package com.zy.baselib.tools;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class PersistUtils {

	private static final String FILE_NAME = "sp_xm";

	private static Application context = null;

	private static SharedPreferences mSp;

	public static void initContext(Application appContext) {
		context = appContext;
		mSp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
	}

	public static void checkeInit() {
		if (context == null) {
			throw new IllegalStateException(
					" app context is null , miss PersistenceUtils.initContext() in applicaiton onCreate");
		}
	}
	public static SharedPreferences getPrefs() {
		checkeInit();
		return mSp;
	}

	public static SharedPreferences.Editor getPrefsEditor() {
		checkeInit();
		return mSp.edit();
	}

	public static void writeInt(String key, int value) {
		checkeInit();
		getPrefsEditor().putInt(key, value).commit();
	}

	public static int readInt(String key) {
		checkeInit();
		return getPrefs().getInt(key, 0);
	}

	public static String readString(String key) {
		checkeInit();
		return getPrefs().getString(key, "");
	}

	public static void writeString(String key, String value) {
		checkeInit();
		getPrefsEditor().putString(key, value).commit();
	}

	public static void deleteString(String key) {
		checkeInit();
		getPrefsEditor().remove(key).apply();
	}

	public static void save(Object obj) {
		checkeInit();
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(context.openFileOutput(obj.getClass()
					.getName(), Context.MODE_PRIVATE));
			oos.writeObject(obj);
			oos.flush();
			oos.close();
		} catch (Exception e) {
		} finally {
			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T load(Class<T> clz) {
		checkeInit();
		T result = null;
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(context.openFileInput(clz.getName()));
			result = (T) ois.readObject();
			ois.close();
		} catch (Exception e) {
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
				}
			}
		}
		return result;
	}

}
